import { createRouter, createWebHashHistory } from "vue-router";
import currencyRoutes from "./modules/currencyRoutes";
import store from "@/store";
const router = createRouter({
  history: createWebHashHistory(),
  routes: currencyRoutes,
  scrollBehavior(to, from, savedPosition) {
    // 始终滚动到顶部
    return { top: 0 };
  },
});
// 导航守卫
router.beforeEach(async (to, from, next) => {
  if (store.getters.token) {
    let { routes } = store.state.Permission;
    if (!routes) {
      await store.dispatch("Permission/MergeRoutes");
      // TODO
      next({ ...to });
    }
    if (to.path === "/login") {
      next("/");
    } else {
      // 浏览器tab名设置
      document.title = `${to.meta.title}—${process.env.VUE_APP_APP_NAME}`;
      // 侧边栏不现实的页面在页面标签栏同样不显示
      if (!to.meta.hidden) {
        store.dispatch("Layout/saveActivePage", to.matched);
      }
      next();
    }
  } else {
    to.path === "/login"
      ? next()
      : next({ path: "/login", query: { redirect: to.fullPath } });
  }
});

export default router;
